package com.examination.controller;

import com.examination.utils.ReflectionUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *  使用一个servlet处理多个请求，其他类继承这个基础类，调用多方法
 *  参考：https://blog.csdn.net/codeMas/article/details/80696777
 */
public class BaseServletController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String methodName = request.getParameter("methodName"); // 调用的方法名称
        if(null != methodName && methodName.length() > 0){

            response.setContentType("text/html;utf-8");
            response.setContentType("text/html;charset=utf-8");
            //执行方法名称
            ReflectionUtil.invoke(this.getClass().getTypeName(), methodName, request , response);
           /* try {
                Method method = this.getClass().getDeclaredMethod(
                        methodName,
                        new Class[] { HttpServletRequest.class,
                                HttpServletResponse.class });
                method.invoke(this, new Object[] { request, response });

            } catch (Exception e) {
                e.printStackTrace();
            }*/
        }
    }

//    @Override
//    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        doPost(request, response);
//    }
//
//    @Override
//    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        request.setCharacterEncoding("UTF-8");
//        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html;charset=utf8");
//        // 获取请求的URI地址信息
//        String url = request.getRequestURI();
//        // 截取其中的方法名
//        String methodName = request.getParameter("methodName");
//        System.out.println("BaseServletController doPost methodName :"+methodName);
//        if(null != methodName && methodName.length() > 0){
//            Method method = null;
//            try {
//                // 使用反射机制获取在本类中声明了的方法
//                method = getClass().getDeclaredMethod(methodName.trim(), HttpServletRequest.class, HttpServletResponse.class);
//                // 执行方法
//                method.invoke(this, request, response);
//                return;
//            } catch (Exception e) {
//                throw new RuntimeException("调用BaseServletController方法出错！methodName没有对应的方法存在。");
//            }
//        }else{
//            throw new RuntimeException("调用BaseServletController方法出错！没有指定methodName的方法名。");
//        }
//
//    }

    /**
     *使用get请求下载文件的时候,由于地址栏用的是iso-8859-1编码格式产生乱码，得到不正确的值,这个要处理下
     * @param request
     * @param key
     * @return
     */
    public String getRequestEncode(HttpServletRequest request,String key){
        String str = request.getParameter(key);
        if(str!=null && str.length() > 0){
            try {
                str = new String(str.getBytes("iso8859-1"),"utf-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return str;
    }
    /**
     * 回写数据的方法，默认是json
     * @param contentType 回写对象类型
     * @param obj 回写的对象数据
     * @param responseOut 响应对象
     * @return 成功--1，失败--0
     */
    public static Integer rendDate(String contentType,String obj,HttpServletResponse responseOut){
        if(null != obj && responseOut != null){
            if(obj instanceof  String){
                if(null != contentType && contentType.length() > 0){
                    responseOut.setContentType(contentType);
                }else{
                    responseOut.setContentType("application/json;charset=utf8");
                }
                try {
                    responseOut.getWriter().write(obj.toString());
                    responseOut.getWriter().flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return 1;
        }
        return 0;
    }
    /**
     *
     * @param model
     * @param request
     * @param <T>
     * @return
     */
    protected <T> T getObjectByRequest(T model,HttpServletRequest request){
        Class c = model.getClass();
        Map<String,String> map = new HashMap();
        Map<String,String[]> parammap = request.getParameterMap();
        for(Map.Entry<String, String[]> entry:parammap.entrySet()){
            String[] value = entry.getValue();
            if(value.length==1){
                map.put(entry.getKey(),value[0]);
            }
        }
        Field[] fields = c.getDeclaredFields();
        try {
            for(int i=0;i<fields.length;i++){
                Field field = fields[i];
                field.setAccessible(true);
                String fname = field.getName();
                String mvalue = map.get(fname);
                if(mvalue != null && !mvalue.equals("") && !mvalue.equals("null")){
                    String ftype = field.getType().getSimpleName();
                    if(ftype.equals("String")){
                        field.set(model, mvalue);
                    }else if(ftype.equals("Integer") || ftype.equals("int")){
                        field.set(model, Integer.parseInt(mvalue));
                    }else if(ftype.equals("Long") || ftype.equals("long")){
                        field.set(model, Long.parseLong(mvalue));
                    }else if(ftype.equals("Float") || ftype.equals("float")){
                        field.set(model, Float.parseFloat(mvalue));
                    }else if(ftype.equals("Double") || ftype.equals("double")){
                        field.set(model, Double.parseDouble(mvalue));
                    }else if(ftype.equals("Timestamp")){
                        Timestamp timestamp = Timestamp.valueOf(mvalue);
                        field.set(model,timestamp);
                    }else if(ftype.equals("Date")){
                        Date date = new Date(mvalue);
                        field.set(model,date);
                    }else if(ftype.equals("Short")){
                        field.set(model, Short.parseShort(mvalue));
                    }
                }
            }
        }catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return model;
    }
}
